<template>
  <a-modal width="450px" v-model:visible="visible" :mask-closable="false" title="添加标签" @cancel="close" @close="close" unmount-on-close>
    <page-form layout="vertical">
      <page-form-row :gutter="24">
        <page-form-item field="endTime" label="违章标签" size="1">
          <sysdict-select
            v-model="data.violationLabelIds"
            multiple
            :popupContainer="'#app'"
            code="violation_label_type"
            @change="onSysdictSelectChange"
            :maxLength="8"
            allow-clear
          />
        </page-form-item>
      </page-form-row>
    </page-form>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="ok" :loading="loading">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { addViolationTag } from '@/api/asset/carViolation'
  import { Notification } from '@arco-design/web-vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
  })

  const data = ref<any>({})
  const loading = ref(false)
  const selectKeys = ref<string[] | number[]>([])

  const emits = defineEmits(['update:modelValue', 'update:okLoading', 'ok'])
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emits('update:modelValue', value),
  })

  const onSysdictSelectChange = (val: number[], label: string) => {
    console.log('onSysdictSelectChange: ', val, label)
    selectKeys.value = val
  }

  const open = (record: any) => {
    console.log('custom-tag-modal: ', record)
    data.value = record
    selectKeys.value = record.violationLabelIds || []
  }

  const ok = () => {
    loading.value = true

    addViolationTag({
      id: data.value.id,
      violationLabelIdList: selectKeys.value,
    })
      .then(() => {
        Notification.success('添加成功')
        close()
        emits('ok')
      })
      .catch(() => {
        Notification.error('添加失败')
      })
      .finally(() => {
        loading.value = false
      })
  }

  const close = () => {
    visible.value = false
    loading.value = false
    selectKeys.value = []
    data.value = {}
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped></style>
